/*
 * Copyright 2018 dc-square GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.hivemq.extensions.rbac.configuration;

import com.hivemq.extension.sdk.api.annotations.NotNull;
import com.hivemq.extension.sdk.api.annotations.Nullable;
import com.hivemq.extension.sdk.api.annotations.ThreadSafe;
import com.hivemq.extensions.rbac.configuration.entities.FileAuthConfig;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * 配置存档备份器
 *
 * @author MI
 */
@ThreadSafe
public class ConfigArchiver {

    private static final Logger log = LoggerFactory.getLogger(ConfigArchiver.class);

    private final @NotNull File archiveFolder;
    private final @NotNull XmlParser xmlParser;

    /**
     * 配置存档器
     * @param extensionHomeFolder  插件文目录
     * @param xmlParser            xml解析器
     */
    ConfigArchiver(@NotNull final File extensionHomeFolder,
                   @NotNull final XmlParser xmlParser) {

        this.xmlParser = xmlParser;
        archiveFolder = new File(extensionHomeFolder, "credentials-archive");
    }

    /**
     * 存档文件夹的配置为XML
     * <p>
     * 如果归档不成功，则此方法将引发IOException.
     * <p>
     * 此方法是线程安全的
     *
     * @param config 要存档的配置
     * @throws IOException 如果发生了不好的情况，并且归档不成功
     */
    public synchronized void archive(@Nullable final FileAuthConfig config) throws IOException {

        if (config == null) {
            log.debug("配置无效，无法归档");
            return;
        }

        // 如果某人讨厌并创建了一个看起来像文件夹的文件
        if (archiveFolder.isFile()) {
            log.warn("凭据存档文件夹是一个文件，正在尝试删除");
            if (archiveFolder.delete()) {
                throw new IOException("无法删除文件" + archiveFolder.getAbsolutePath());
            }
        }

        // 如果有人同时删除了该文件夹
        if (!archiveFolder.exists()) {

            log.debug("创建凭据存档文件夹");

            if (!archiveFolder.mkdir()) {
                throw new IOException("无法创建凭据存档文件夹 " + archiveFolder.getAbsolutePath());
            } else {
                log.info("创建的凭证存档文件夹 {}." + archiveFolder.getAbsolutePath());
            }
        }

        final FastDateFormat formatter = FastDateFormat.getInstance("yyyyMMdd-hh-mm-ss");
        try {
            final String dateString = formatter.format(new Date());
            final File file = new File(archiveFolder, dateString + "-credentials.xml");
            xmlParser.marshal(config, file);
            log.info("存档的当前凭据配置为 {}.", file.getAbsolutePath());
        } catch (NotMarshallableException e) {
            throw new IOException(e);
        }
    }

}
